package com.cs.micro.file.web;

import com.cs.base.common.support.FileResult;
import com.cs.base.common.support.SimpleResult;
import com.cs.base.common.support.SimpleStatusCode;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * @author wangjiahao
 * @version 1.0
 * @className UploadCtrl
 * @since 2019-02-25 11:18
 */
@Slf4j
@RestController
@Api(tags = "文件上传")
public class UploadCtrl {

    @Autowired
    private FastFileStorageClient client;

    @ApiOperation(value = "文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件流对象", required = true, dataType = "MultipartFile"),
            @ApiImplicitParam(name = "title", value = "title", required = true)
    })
    @PostMapping(value = "/i/uploadFile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public SimpleResult<FileResult> uploadImage(@RequestParam(value = "file") MultipartFile file,
                                                @RequestParam(value = "title") String title) throws Exception {

        if (Objects.isNull(file)) {
            return SimpleResult.build(SimpleStatusCode.FAIL);
        }
        log.debug("upfile.getOriginalFilename() = " + file.getOriginalFilename());

        StorePath storePath = client.uploadFile(
                file.getInputStream(), file.getSize(), "png", null);

        FileResult result = new FileResult();

        result.setFilename(file.getOriginalFilename());
        result.setTitle(title);
        result.setUrl(storePath.getFullPath());

        return SimpleResult.ok(result);
    }
}
